package com.project.livetv.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.google.gson.Gson;
import com.project.livetv.R;
import com.project.livetv.activity.MainTVShowActivity;
import com.project.livetv.adapter.MyHotTabAdapter;
import com.project.livetv.adapter.MyPageAdapter;
import com.project.livetv.bean.LatestBean;
import com.project.livetv.callback.NetCallBack;
import com.project.livetv.config.NetConfig;

import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by li on 2016/5/9.
 */
public class HotFragment extends BaseFragment implements ViewPager.OnPageChangeListener, AdapterView.OnItemClickListener, AbsListView.OnScrollListener {

    private ViewPager hotViewpager;
    private ListView mListView;
    private List<View> views;
    private MyPageAdapter pageradapter;
    private List<LatestBean.LivesBean> data;
    private MyHotTabAdapter topAdapter;
    private int position;

    private List<String> imgUrls;

    private boolean mFlag;
    private Timer timer;

    private ProgressDialog mDialog;

    private PullRefreshLayout mPullRefreshLayout;

    List<ImageView> pointList;
    private ImageView first_icon, second_icon, third_icon, forth_icon, fivith_icon, sixth_icon, seventh_icon;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    position++;
                    hotViewpager.setCurrentItem(position);
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        views = new ArrayList<>();
        data = new ArrayList<>();

        pointList = new ArrayList<>();
        pageradapter = new MyPageAdapter(views);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.hot_fragment_layout, container, false);
        View headView = inflater.inflate(R.layout.list_top_view, null);

        hotViewpager = (ViewPager) headView.findViewById(R.id.viewpager_hottab_position);
        mListView = (ListView) rootView.findViewById(R.id.listView_hottab_position);
        mListView.addHeaderView(headView);
        // first_icon,second_icon,third_icon,forth_icon,fivith_icon,sixth_icon,seventh_icon;

        first_icon = (ImageView) headView.findViewById(R.id.first_point);
        second_icon = (ImageView) headView.findViewById(R.id.second_point);
        third_icon = (ImageView) headView.findViewById(R.id.third_point);
        forth_icon = (ImageView) headView.findViewById(R.id.forth_point);
        fivith_icon = (ImageView) headView.findViewById(R.id.fivth_point);
        sixth_icon = (ImageView) headView.findViewById(R.id.sixth_point);
        seventh_icon = (ImageView) headView.findViewById(R.id.seventh_point);

        first_icon.setSelected(true);
        // pointList.add(seventh_icon);
        pointList.add(first_icon);
        pointList.add(second_icon);
        pointList.add(third_icon);
        pointList.add(forth_icon);
        pointList.add(fivith_icon);
        pointList.add(sixth_icon);
        pointList.add(seventh_icon);
        pointList.add(first_icon);
        hotViewpager.setCurrentItem(1);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = Message.obtain();
                message.what = 1;
                handler.sendEmptyMessageDelayed(message.what, 2000);
            }
        }, 0, 2000);

        //进度对话框
        mDialog = new ProgressDialog(getContext());

        imgUrls = new ArrayList<>();
        imgUrls.add("NDAwMjcxNDYyOTYwOTg4.jpg");
        imgUrls.add("NjU2NDIxNDYxOTQ2MTMy.jpg");
        imgUrls.add("ODEwNTQxNDYyOTQ4ODM3.jpg");
        imgUrls.add("NzEyMTAxNDYxMzE2NDA3.jpg");
        imgUrls.add("ODMxMjUxNDYyOTAwMTcy.jpg");
        imgUrls.add("NDIyMDcxNDYyMjQ3NzY1.jpg");
        imgUrls.add("NDM1NDIxNDYxOTI5MjY0.jpg");

        //刷新
        mPullRefreshLayout = (PullRefreshLayout) rootView.findViewById(R.id.prfl_hotFragment_refresh);

        setData();
        setListener();
        return rootView;
    }

    private void setListener() {
        mPullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                data.clear();
                downLoadDataInHot(3);
                mPullRefreshLayout.setRefreshing(false);
            }
        });

        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(this);
    }

    private void setData() {

        downLoadDataInHot(3);


        for (int i = 0; i < 7; i++) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.tab_hot_layout, null);
            ImageView imageview = (ImageView) view.findViewById(R.id.imageview_tab_viewpager_position);
            x.image().bind(imageview, NetConfig.MAIN_TV_HOT_IMAGE1 + imgUrls.get(i) + NetConfig.MAIN_TV_HOT_IMAGE2);
            views.add(view);
        }
        hotViewpager.setAdapter(pageradapter);
        topAdapter = new MyHotTabAdapter(getContext(), data);
        mListView.setAdapter(topAdapter);
        setListViewHeight(mListView);
        hotViewpager.addOnPageChangeListener(this);


    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.position = position;
        for (int i = 0; i < pointList.size(); i++) {
            pointList.get(i).setSelected(i == position);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (position == views.size() - 1 && state == ViewPager.SCROLL_STATE_IDLE) {
            position = 0;
            hotViewpager.setCurrentItem(position, false);

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hotViewpager.removeOnPageChangeListener(this);
        timer.cancel();
        timer = null;
    }


    public void setListViewHeight(ListView listView) {

        // 获取ListView对应的Adapter

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    /**
     * 下载数据
     */

    private void downLoadDataInHot(int page) {
        String url = NetConfig.NEW_DATA1 + page + NetConfig.NEW_DATA2;
        downLoadData(url, new NetCallBack() {
            @Override
            public void onStart() {
                mDialog.show();

            }

            @Override
            public void onSucess(String result) {
                Gson gson = new Gson();
                LatestBean latestBean = gson.fromJson(result, LatestBean.class);
                List<LatestBean.LivesBean> tempData = latestBean.getLives();
                data.addAll(tempData);
                Log.d("tag", "listsize  " + data.size());
                topAdapter.notifyDataSetChanged();
                mPullRefreshLayout.setRefreshing(false);
                mDialog.dismiss();

            }

            @Override
            public void onError(String error) {
                mDialog.dismiss();
                Toast.makeText(getContext(), R.string.netError, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFinished() {
                mDialog.dismiss();

            }

            @Override
            public void onCancled() {
                mDialog.dismiss();

            }
        });
    }

    /**
     * 单击
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getContext(), MainTVShowActivity.class);
        intent.putExtra("ypNum",data.get(position).getCreator().getId());
        intent.putExtra("roomNum",data.get(position).getId());
        intent.putExtra("livePeos",data.get(position).getOnline_users());
        intent.putExtra("tvUrl", data.get(position - 1).getStream_addr());
        startActivity(intent);
    }

    /**
     * 分页加载
     *
     * @param view
     * @param scrollState
     */

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE && mFlag) {
            downLoadDataInHot(3);
            mPullRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        if (firstVisibleItem + visibleItemCount == totalItemCount) {
            mFlag = true;
        } else {
            mFlag = false;
        }
    }
}
